import { defineStore } from 'pinia'
import { login as loginApi } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => {
    // 从 localStorage 恢复用户信息
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedPermissions = localStorage.getItem('permissions')
    const token = localStorage.getItem('token')
    
    return {
      // 用户信息 - 从 localStorage 恢复或使用默认值
      userInfo: savedUserInfo ? JSON.parse(savedUserInfo) : {
        id: null,
        name: '',
        username: '',
        email: '',
        avatar: '',
        phone: '',
        department: '',
        role: ''
      },
      
      // 用户权限 - 从 localStorage 恢复或使用空数组
      permissions: savedPermissions ? JSON.parse(savedPermissions) : [],
      
      // 登录状态 - 根据 token 判断
      isLoggedIn: !!token,
      
      // 登录token - 从 localStorage 恢复
      token: token || ''
    }
  },

  getters: {
    // 检查用户是否有指定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },

    // 检查用户是否有任一权限
    hasAnyPermission: (state) => (permissions) => {
      return permissions.some(permission => state.permissions.includes(permission))
    },

    // 检查用户是否有所有权限
    hasAllPermissions: (state) => (permissions) => {
      return permissions.every(permission => state.permissions.includes(permission))
    },

    // 获取用户角色
    userRole: (state) => state.userInfo.role,

    // 是否为管理员
    isAdmin: (state) => state.userInfo.role === '系统管理员'
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      // 同步保存到 localStorage
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },

    // 设置用户权限
    setPermissions(permissions) {
      this.permissions = permissions
      // 同步保存到 localStorage
      localStorage.setItem('permissions', JSON.stringify(permissions))
    },

    // 设置登录状态
    setLoggedIn(isLoggedIn) {
      this.isLoggedIn = isLoggedIn
    },

    // 设置token
    setToken(token) {
      this.token = token
      // 同步保存到 localStorage
      localStorage.setItem('token', token)
    },

    // 登录
    async login(credentials) {
      // 调用登录API - POST /user/login
      const response = await loginApi({
        username: credentials.username,
        password: credentials.password
      })
      
      // code === 200 时保存用户信息
      if (response.code === 200 && response.data) {
        const userData = response.data
        
        // 映射后端字段到前端字段
        const userInfo = {
          id: userData.id,
          name: userData.name || '',
          username: credentials.username, // 后端没返回，用登录时的用户名
          email: userData.email || '',
          avatar: userData.avatar || '',
          phone: userData.phone || '',
          department: userData.structureName || '', // 部门名称
          role: userData.dataScopeName || '', // 数据范围作为角色
          accountNo: userData.accountNo || '',
          dataScope: userData.dataScope || '',
          structureIds: userData.structureIds || '',
          note: userData.note || ''
        }
        
        this.setUserInfo(userInfo)
        
        // 保存 sessionId 作为 token
        if (userData.sessionId) {
          this.setToken(userData.sessionId)
          localStorage.setItem('sessionId', userData.sessionId)
        }
        
        // 根据 dataScope 设置默认权限
        const defaultPermissions = this.generatePermissions(userData.dataScope)
        this.setPermissions(defaultPermissions)
        
        this.setLoggedIn(true)
      }
      
      // 直接返回后端响应，由调用方判断 code
      return response
    },
    
    // 根据数据范围生成权限列表
    generatePermissions(dataScope) {
      // 根据实际业务需求调整权限
      const basePermissions = [
        'user:view',
        'inventory:view',
        'purchase:view',
        'sales:view'
      ]
      
      // 如果是 'my' 只能查看自己相关的数据
      if (dataScope === 'my') {
        return basePermissions
      }
      
      // 其他数据范围给予更多权限
      return [
        ...basePermissions,
        'user:create', 'user:edit', 'user:delete',
        'inventory:create', 'inventory:edit', 'inventory:delete',
        'purchase:create', 'purchase:edit', 'purchase:delete',
        'sales:create', 'sales:edit', 'sales:delete',
        'finance:view', 'finance:create', 'finance:edit', 'finance:delete'
      ]
    },

    // 登出
    logout() {
      this.userInfo = {
        id: null,
        name: '',
        username: '',
        email: '',
        avatar: '',
        phone: '',
        department: '',
        role: ''
      }
      this.permissions = []
      this.token = ''
      this.isLoggedIn = false
      
      // 清理 localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('sessionId')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
    },

    // 模拟登录API
    async mockLogin(credentials) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (credentials.username === 'admin' && credentials.password === '123456') {
            resolve({
              userInfo: {
                id: 1,
                name: '管理员',
                username: 'admin',
                email: 'admin@example.com',
                avatar: '',
                phone: '13800138000',
                department: '技术部',
                role: '系统管理员'
              },
              permissions: [
                'user:view', 'user:create', 'user:edit', 'user:delete',
                'role:view', 'role:create', 'role:edit', 'role:delete',
                'inventory:view', 'inventory:create', 'inventory:edit', 'inventory:delete',
                'purchase:view', 'purchase:create', 'purchase:edit', 'purchase:delete',
                'sales:view', 'sales:create', 'sales:edit', 'sales:delete',
                'finance:view', 'finance:create', 'finance:edit', 'finance:delete'
              ],
              token: 'mock-token-' + Date.now()
            })
          } else {
            reject(new Error('用户名或密码错误'))
          }
        }, 1000)
      })
    }
  }
})
